package cn.gary.oaserver.config.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @Author: 邓必宏
 * @title: 、
 * @Demo:
 * @DateTime: 2024/4/9
 */

@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {


    @Override           //用户拥有的权限
    public void decide(Authentication authentication, Object o,
                       //通过SecurityConfig.createList()方法设置的权限
                       Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute configAttribute : collection) {
            String attribute = configAttribute.getAttribute ( );
            System.out.println ("可请求的角色" );
            if (attribute.equals ( "ROLE_LOGIN" )) {
                //判断是否登录
                if (authentication instanceof AnonymousAuthenticationToken) {
                    throw new AccessDeniedException ( "尚未登录，请登录!" );
                } else {
                    return;
                }
            }
            //请求其他路径再与用户的权限进行配对配对成功就放行
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities ( );
            for (GrantedAuthority authority : authorities) {
                if (attribute.equals ( authority.getAuthority () )) {
                    System.out.println ("可访问" );
                    return;
                }
            }
        }
        //如果都没权限那就是无权访问
        throw new AccessDeniedException ( "权限不足，请联系管理员!" );
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
